// 2025/4/5
// https://leetcode.cn/problems/3sum/description/?envType=study-plan-v2&envId=top-100-liked
// 三数之和

class Solution {
    public:
        vector<vector<int>> threeSum(vector<int>& nums) {
            sort(nums.begin(), nums.end());
            int n = nums.size();
            vector<vector<int>> ans;
            for(int i = 0; i < n - 2; i++)
            {
                if(i > 0 && nums[i] == nums[i - 1]) continue;
                int left = i + 1, right = n - 1;
                while(left < right)
                {
                    int tmp = nums[i] + nums[left] + nums[right];
                    if(tmp < 0) left++;
                    else if(tmp > 0) right--;
                    else
                    {
                        ans.push_back({nums[i], nums[left], nums[right]});
                        while(left < right && nums[left] == nums[++left]);
                        while(left < right && nums[right] == nums[--right]);
                    }
                }
            }
            
            return ans;
        }
    };